<template>
	<view class="container">
		<view class="input-bibox">
			<view class="input-box">
				<input type="text" class="input-field" placeholder="请输入17位车架号" v-model="vinCode" />
				<!-- 相机图标 -->
				<image @click="photoAlbum" src="/static/images/xiangji.png" class="search-xiangji"></image>
			</view>
			<!-- 搜索图标移出到外部 -->
			<button @click="searchVin()" class="search-btn">搜索</button>
		</view>

		<view v-if="showDetail" class="address-book-container">
			<!-- 设置为可滚动区域，占据剩余空间 -->
			<scroll-view class="scroll-container uni-list" scroll-y="true" scroll-with-animation="true">
				<!-- 标题区域（灰色透明框） -->
				<view class="title-box" v-if="keyword">
					<view class="model-detail" @click="searchCarDetail">{{keyword}}</view>
				</view>
				<CarDetail :carInfo="carInfo" :title="modelDetail" :imgUrl="img" />
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import CarDetail from '@/pages/commponent/car_detail_moudel.vue'; // 引入组件
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		vinCode,
		searchCarDetail,
	} from '@/api/car.js';
	import {
		mapGetters
	} from "vuex";
	import {
		HEADER,
		HTTP_REQUEST_URL,
	} from '@/config/app';
	export default {
		components: {
			CarDetail,
		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
				userType: 'userType',
				bgUserType: 'bgUserType'
			}),
		},
		data() {
			return {
				carInfo: {},
				showDetail: false,
				vinCode: '',
				vin: '',
				modelDetail: '',
				brand: '',
				series: '',
				modelYear: '',
				model: '',
				modelId: '',
				salesVersion: '',
				cc: '',
				factory: '',
				img: '',
				keyword: '',
			}
		},
		onLoad(options) {
			if (options.vinCode) {
				this.vinCode = options.vinCode;
				this.searchVin();
			}
		},
		methods: {
			/**
			 * 分享
			 */
			shareCard() {
				uni.showShareMenu({
					//小程序的原生菜单中显示分享按钮，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
					menus: ["shareAppMessage", "shareTimeline"] //不设置默认发送给朋友
				})
			},
			// 分享到朋友
			onShareAppMessage(res) {
				let that = this;
				//这块需要传参，不然链接地址进去获取不到数据
				return {
					title: that.title,
					path: 'pages/commponent/car_vin?vinCode=' + that.vinCode,
					imageUrl: ''
				};
			},

			//分享到朋友圈
			onShareTimeline(res) {
				let that = this;
				//这块需要传参，不然链接地址进去获取不到数据
				return {
					title: that.title,
					path: 'pages/commponent/car_vin?vinCode=' + that.vinCode,
					imageUrl: ''
				};
			},
			photoAlbum() {
				// 打开相机拍照
				uni.chooseImage({
					count: 1, // 只能选择一张图片
					sourceType: ['album'], // 允许使用相机和相册
					success: (res) => {
						// 获取图片路径
						const filePath = res.tempFilePaths[0];
						console.log('识别成功，图片路径:', filePath);
						// 压缩图片
						uni.compressImage({
							src: filePath,
							quality: 80, // 质量 80%
							success: (compressRes) => {
								const compressedPath = compressRes.tempFilePath;
								// 上传图片文件
								this.uploadImage(compressedPath); // 上传压缩后的图片文件
								this.cameraOn = false;
								this.showButtons = false;
							},
							fail: (err) => {
								uni.showToast({
									title: '图片压缩失败',
									icon: 'none',
								});
							}
						});
					},
					fail: (err) => {
						console.error('识别取消:', err);
						uni.showToast({
							title: '识别取消',
							icon: 'none',
						});
					}
				});

			},
			// 上传图片文件
			uploadImage(filePath) {
				if (this.isLogin == false) {
					toLogin();
					return;
				}
				// 显示加载提示
				uni.showLoading({
					title: '处理中...',
					mask: true, // 遮罩层，防止用户点击其他区域
				});
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/car/getMd5Token',
					//url: 'http://localhost:8930/car/getMd5Token',
					filePath: filePath,
					name: 'file', // 参数名，后端获取的字段
					success: (uploadRes) => {
						console.log('上传成功:', uploadRes.data);
						// 如果后端返回的字符串是 JSON 格式，尝试解析
						try {
							const parsedData = JSON.parse(uploadRes.data);
							console.log(parsedData)
							this.callVinApi(parsedData); // 将解析后的数据传递给下一个函数
						} catch (error) {
							console.error("JSON 解析失败:", error);
						}
					},
					fail: (err) => {
						console.error('未识别到有效信息:', err);
						uni.showToast({
							title: '未识别到有效信息，请重试',
							icon: 'none',
						});
					},
					complete: () => {
						console.log(this.modelDetail);
						// 无论请求成功或失败，都隐藏加载提示
						uni.hideLoading();
					}
				});
			},
			searchVin() { //输入框查询车架号
				if (!this.vinCode || this.vinCode.length !== 17) {
					uni.showToast({
						title: '请输入17位有效车架号',
						icon: 'none',
					});
					return;
				}
				if (this.isLogin == false) {
					toLogin();
					return;
				}
				vinCode({
					vinCode: this.vinCode
				}).then(res => {
					this.callVinApi(res);
				}).catch(err => {
					console.error("请求失败，错误信息：", err); // 打印错误信息
					this.$util.Tips({
						title: "根据车架号查询错误"
					});
				});
			},
			// 根据返回内容查询
			callVinApi(uploadResponse) {
				// 判断 uploadResponse 和 uploadResponse.value 是否为 null 或 undefined
				if (!uploadResponse || !uploadResponse.value) {
					uni.showToast({
						title: '数据为空',
						icon: 'none',
					});
					return; // 如果上传响应数据不合法，直接返回，不继续执行后面的逻辑
				}
				const {
					brand,
					series,
					modelDetail,
					Model,
					vin,
					modelYear,
					salesVersion,
					cc,
					factory,
					img,
				} = uploadResponse.value;
				// 连接品牌和系列
				const brandModel = `${factory}${Model}`;

				this.modelDetail = `${modelDetail}`;
				this.vin = `${vin}`;
				this.brand = `${brand}`
				this.series = `${series}`
				this.model = `${Model}`
				this.modelYear = `${modelYear}`
				this.salesVersion = `${salesVersion}`
				this.cc = `${cc}`
				this.factory = `${factory}`
				this.img = `${img}`

				this.keyword = this.modelDetail;
				console.log("搜索条件：" + brandModel)

				this.searchCarDetail();
				this.vinCode = this.vin
			},
			searchCarDetail() {
				this.showDetail = false;
				// 查具体信息 wxCar 表内容
				searchCarDetail({
					factory: this.factory,
					model: this.model,
					modelYear: this.modelYear,
					salesVersion: this.salesVersion,
					cc: this.cc,
					brand: this.brand,
					userId: this.uid
				}).then(res => {
					console.log(this.model);
					if (res.value != null) {
						this.carInfo = res.value;
						console.log("有具体车型：" + res.value.carId);
						const jinDeng = this.carInfo.jinDeng;
						const yuanDeng = this.carInfo.yuanDeng;
						const wuDeng = this.carInfo.wuDeng;
						// 判断字段是否为空、null 或 undefined
						this.showDetail = true;
					} else {
						this.carInfo = [];
						// 提示暂无信息
						console.log("无具体车型：" + this.modelDetail);
					}
				}).catch(error => {
					console.error("查询具体车型失败：", error);
					// 可选：捕获错误并提示
					uni.showToast({
						title: '查询失败，请稍后重试',
						icon: 'none',
						duration: 2000
					});
				});
			}
		}
	}
</script>

<style>
	/* 页面样式 */
	.container {
		padding: 20px;
		/* 可以根据需要调整顶部的 padding */
	}

	.input-bibox {
		display: flex;
		justify-content: space-between;
		/* 水平两端对齐，使搜索按钮在右侧 */
		align-items: center;
		/* 垂直居中 */
	}

	.input-box {
		display: flex;
		align-items: center;
		border: 1px solid #ccc;
		border-radius: 8rpx;
		padding: 10rpx 15rpx;
		background-color: #f9f9f9;
		width: calc(100% - 120rpx);
		/* 减去搜索按钮的宽度 */
		flex: 1;
		/* 让输入框占据剩余空间 */
		margin-right: 10px;
		/* 为搜索按钮留出空间 */
	}

	.input-field {
		flex: 1;
		height: 40rpx;
		font-size: 30rpx;
		border: none;
		outline: none;
		background-color: transparent;
	}

	.search-xiangji {
		width: 60rpx;
		height: 60rpx;
	}

	.search-btn {
		background-color: #4CAF50;
		/* 添加底色 */
		color: white;
		border: none;
		/* 移除按钮的边框 */
		border-radius: 10rpx;
		/* 按钮圆角 */
		cursor: pointer;
	}
</style>